﻿using System.Collections.ObjectModel;
using CommunityToolkit.Mvvm.Input;
using ContactSMS.Client.Models;
using ContactSMS.Client.SearchHandlers;
using ContactSMS.Client.Views;
using ContactSMS.UseCases.PluginInterfaces;
using ContactCoreBusiness = ContactSMS.CoreBusiness.Contact;
using CommunityToolkit.Mvvm.ComponentModel;
using System.Xml.Linq;

namespace ContactSMS.Client.ViewModels
{
    public partial class CommonSearchViewModel : ObservableObject
    {
        private readonly IContactRepository contactRepository;

        public ObservableCollection<ContactCoreBusiness> Contacts { get; set; }

        public CommonSearchViewModel(IContactRepository contactRepository)
        {
            this.Contacts = new ObservableCollection<ContactCoreBusiness>();
            this.contactRepository = contactRepository;
        }

        [RelayCommand]
        public async Task SearchContact(object o)
        {
            var contactSearchHandler = o as ContactSearchHandler;
            var search = contactSearchHandler.Query;
            this.Contacts.Clear();
            var contacts = await this.contactRepository.GetContactsAsync(search);
            if (contacts != null && contacts.Count > 0)
            {
                foreach (var contact in contacts)
                {
                    this.Contacts.Add(contact);
                }
            }
            //contactSearchHandler.ItemsSource = this.Contacts;
            //await LoadContactAsync(search);
        }

        public async Task LoadContactAsync()
        {
            var contacts = await this.contactRepository.GetContactsAsync(string.Empty);
            if (contacts != null && contacts.Count > 0)
            {
                foreach (var contact in contacts)
                {
                    this.Contacts.Add(contact);
                }
            }
        }
    }
}
